package com.yuan.zsschool.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yuan.base.common.KeyboardChangeListener;
import com.yuan.base.framework.BaseFrameworkActivity;
import com.yuan.base.framework.BaseTokenManager;
import com.yuan.base.framework.http.BaseHttpRequest;
import com.yuan.base.utils.ActivityManager;
import com.yuan.base.utils.PreferencesUtils;
import com.yuan.zsschool.Constant;
import com.yuan.zsschool.R;
import com.yuan.zsschool.Urls;
import com.yuan.zsschool.ui.account.FindPwdActivity;
import com.yuan.zsschool.ui.account.RegisterActivity;

import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.app.RequestInterceptListener;
import org.xutils.http.request.UriRequest;
import org.xutils.x;

import java.util.HashMap;


public class LoginActivity extends BaseFrameworkActivity {

	private static final int REQUEST_EXTERNAL_STORAGE = 1;
	private static String[] PERMISSIONS_STORAGE = {
			Manifest.permission.READ_EXTERNAL_STORAGE,
			Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.ACCESS_FINE_LOCATION,
			Manifest.permission.CAMERA
	};

	private TextView tv_user_protocol;
	private EditText et_user_code;
	private EditText et_user_pwd;
	private ImageView iv_clear_user;
	private ImageView iv_show_pwd;
	private FrameLayout fl_head;
	private RelativeLayout rl_title_layout;
	private Button btn_submit;
	private boolean isShowPwd = false;
	private CheckBox chk_user_protocol;

	@Override
	protected int getLayoutId() {
		return R.layout.activity_login;
	}

	@Override
	protected void bindViews() {
		tv_user_protocol = findViewById(R.id.tv_user_protocol);
		et_user_code = findViewById(R.id.et_user_code);
		et_user_pwd = findViewById(R.id.et_user_pwd);
		iv_clear_user = findViewById(R.id.iv_clear_user);
		iv_show_pwd = findViewById(R.id.iv_show_pwd);
		fl_head = findViewById(R.id.fl_head);
		rl_title_layout = findViewById(R.id.rl_title_layout);
		btn_submit = findViewById(R.id.btn_submit);
		chk_user_protocol = findViewById(R.id.chk_user_protocol);

		chk_user_protocol.setOnCheckedChangeListener((buttonView, isChecked) -> {
			PreferencesUtils.putBoolean(LoginActivity.this, Constant.Preferences.IS_READ_USER_PROTOCOL, isChecked);
		});
		btn_submit.setOnClickListener(v -> login());
		setOnClickListener(R.id.tv_to_register, v -> {
			startActivity(new Intent(this, RegisterActivity.class));
		});
		setOnClickListener(R.id.tv_to_find_pwd, v -> {
			startActivity(new Intent(this, FindPwdActivity.class));
		});
		iv_clear_user.setOnClickListener(v -> {
			et_user_code.setText("");
			v.setVisibility(View.GONE);
		});
		et_user_code.addTextChangedListener(new CodeWatcher());
		iv_show_pwd.setOnClickListener(v -> {
			if (isShowPwd) {
				iv_show_pwd.setImageResource(R.drawable.ic_login_pwd_hide);
				et_user_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
				et_user_pwd.setSelection(et_user_pwd.getText().toString().length());
			} else {
				iv_show_pwd.setImageResource(R.drawable.ic_login_pwd_show);
				et_user_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
				et_user_pwd.setSelection(et_user_pwd.getText().toString().length());
			}
			isShowPwd = !isShowPwd;
		});
		new KeyboardChangeListener(this).setKeyBoardListener((isShow, keyboardHeight) -> {
			if (isShow) {
				rl_title_layout.setVisibility(View.VISIBLE);
				fl_head.setVisibility(View.GONE);
			} else {
				rl_title_layout.setVisibility(View.GONE);
				fl_head.setVisibility(View.VISIBLE);
			}
		});
	}


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		putNotHideViewId(et_user_code);
		putNotHideViewId(et_user_pwd);
		putNotHideViewId(iv_clear_user);
		putNotHideViewId(iv_show_pwd);

		BaseTokenManager.setToken(null);

		// 6.0之后申请权限
		for (String aPERMISSIONS_STORAGE : PERMISSIONS_STORAGE) {
			if (ActivityCompat.checkSelfPermission(this, aPERMISSIONS_STORAGE) != PackageManager.PERMISSION_GRANTED) {
				ActivityCompat.requestPermissions(
						this,
						PERMISSIONS_STORAGE,
						REQUEST_EXTERNAL_STORAGE
				);
			}
		}

		init();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (TextUtils.isEmpty(getIntent().getStringExtra("userCode"))) {
			et_user_code.setText(PreferencesUtils.getString(this, Constant.Preferences.USER_CODE, ""));
		}
		chk_user_protocol.setChecked(PreferencesUtils.getBoolean(this, Constant.Preferences.IS_READ_USER_PROTOCOL, false));
	}

	// 初始化
	private void init() {
		if (!TextUtils.isEmpty(getIntent().getStringExtra("userCode"))) {
			et_user_code.setText(getIntent().getStringExtra("userCode"));
			et_user_pwd.setText("");
		}
//		et_user_code.setText(PreferencesUtils.getString(this, Constant.Preferences.USER_CODE));
//		et_user_code.setSelection(et_user_code.getText().toString().length());
//		chk_save_pwd.setChecked(PreferencesUtils.getBoolean(this, Constant.Preferences.SAVE_PWD_STATE, false));

		String str = "已阅读并同意《" + getString(R.string.app_name) + "用户协议》";
		SpannableString spannableString = new SpannableString(str);
		spannableString.setSpan(new ClickableSpan() {
			@Override
			public void onClick(View widget) {
				// 打开用户协议
				startActivity(new Intent(LoginActivity.this, H5Activity.class));
			}
		}, str.indexOf("《"), str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		tv_user_protocol.setText(spannableString);
		tv_user_protocol.setHighlightColor(getColorBase(R.color.transparent));
		tv_user_protocol.setMovementMethod(LinkMovementMethod.getInstance());

	}

	public void login() {
		String code = getStringByUI(et_user_code).replaceAll(" ", "");
		if (TextUtils.isEmpty(code)) {
			showToast("请输入手机号");
			return;
		}
		if (code.length() != 11) {
			showToast("请输入正确的手机号码");
			return;
		}
		if (TextUtils.isEmpty(getStringByUI(et_user_pwd))) {
			showToast("请输入密码");
			return;
		}
		if (!chk_user_protocol.isChecked()) {
			showToast("请仔细阅读用户协议并同意");
			return;
		}

		HashMap<String, Object> params = new HashMap<>();
		params.put("username", code);
		params.put("password", getStringByUI(et_user_pwd));
		RequestParams p = BaseHttpRequest.getRequestParams(HttpMethod.POST, Urls.getUrl(Urls.login), params, null);
		showProgressBar("正在登录...");
		x.http().post(p, new LoginCallback());
	}

	private class LoginCallback implements Callback.CommonCallback<String>, RequestInterceptListener {
		@Override
		public void beforeRequest(UriRequest request) {
		}

		@Override
		public void afterRequest(UriRequest request) {
			runOnUiThread(() -> {//request.getResponseHeaders()
				if (TextUtils.isEmpty(request.getResponseHeader("Authorization"))) {
					showToast("用户名或密码错误");
				} else {
					PreferencesUtils.putString(LoginActivity.this, Constant.Preferences.USER_CODE, getStringByUI(et_user_code).replaceAll(" ", ""));
					PreferencesUtils.putString(LoginActivity.this, Constant.Preferences.USER_PWD, getStringByUI(et_user_pwd));
//					PreferencesUtils.putBoolean(LoginActivity.this, Constant.Preferences.SAVE_PWD_STATE, chk_save_pwd.isChecked());
					loginSuccess(request.getResponseHeader("Authorization"));
				}
			});
		}

		@Override
		public void onSuccess(String result) {
		}

		@Override
		public void onError(Throwable ex, boolean isOnCallback) {
			ex.printStackTrace();
		}

		@Override
		public void onCancelled(CancelledException cex) {
		}

		@Override
		public void onFinished() {
			hideProgressBar();
		}
	}

	private void loginSuccess(String authorization) {
		BaseTokenManager.setToken(authorization);
		Intent intent = new Intent(LoginActivity.this, MainActivity.class);
		startActivity(intent);
		closeSelf();
	}

	@Override
	public void onBackPressed() {
		ActivityManager.getInstance().popAllActivity();
		System.exit(0);
	}

	private class CodeWatcher implements TextWatcher {
		int beforeTextLength = 0;
		int onTextLength = 0;
		boolean isChanged = false;

		int location = 0;// 记录光标的位置
		private char[] tempChar;
		private StringBuffer buffer = new StringBuffer();
		int konggeNumberB = 0;

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			onTextLength = s.length();
			buffer.append(s.toString());
			if (onTextLength == beforeTextLength || onTextLength <= 3 || isChanged) {
				isChanged = false;
				return;
			}
			isChanged = true;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			beforeTextLength = s.length();
			if (buffer.length() > 0) {
				buffer.delete(0, buffer.length());
			}
			konggeNumberB = 0;
			for (int i = 0; i < s.length(); i++) {
				if (s.charAt(i) == ' ') {
					konggeNumberB++;
				}
			}
		}

		@Override
		public void afterTextChanged(Editable s) {
			iv_clear_user.setVisibility(TextUtils.isEmpty(s.toString()) ? View.GONE : View.VISIBLE);
			if (isChanged) {
				location = et_user_code.getSelectionEnd();
				int index = 0;
				while (index < buffer.length()) {
					if (buffer.charAt(index) == ' ') {
						buffer.deleteCharAt(index);
					} else {
						index++;
					}
				}

				index = 0;
				int konggeNumberC = 0;
				while (index < buffer.length()) {
					if ((index == 3 || index == 8)) {
						buffer.insert(index, ' ');
						konggeNumberC++;
					}
					index++;
				}

				if (konggeNumberC > konggeNumberB) {
					location += (konggeNumberC - konggeNumberB);
				}

				tempChar = new char[buffer.length()];
				buffer.getChars(0, buffer.length(), tempChar, 0);
				String str = buffer.toString();
				if (location > str.length()) {
					location = str.length();
				} else if (location < 0) {
					location = 0;
				}

				et_user_code.setText(str);
				Editable etable = et_user_code.getText();
				Selection.setSelection(etable, location);
				isChanged = false;
			}
		}

	}
}

